package com.jww.servlet.bill;

import com.alibaba.fastjson.JSONArray;
import com.jww.pojo.User;
import com.jww.service.provider.providerService;
import com.jww.service.provider.providerServiceImpl;
import com.jww.pojo.Bill;
import com.jww.pojo.Provider;
import com.jww.service.bill.BillService;
import com.jww.service.bill.BillServiceImpl;
import com.jww.util.Constants;
import com.jww.util.PageSupport;
import com.mysql.jdbc.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

public class BillServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method"); // 获取前端的键值对method对应的值
        if (method != null && method.equals("query")) {
            this.query(req, resp);
        } else if (method != null && method.equals("add")) {
            this.add(req, resp);
        } else if (method != null && method.equals("getproviderlist")) {
            this.getProviderList(req, resp);
        } else if (method != null && method.equals("view")) {
            this.getBillId(req, resp, "billview.jsp");
        } else if (method != null && method.equals("modifysave")) {
            this.updateBill(req, resp);
        } else if (method != null && method.equals("modify")) {
            this.getBillId(req, resp, "billmodify.jsp");
        } else if (method != null && method.equals("delbill")) {
            this.deleteBill(req, resp);
        } else if (method != null && method.equals("selectBillCodeExist")) {
            this.selectBillCodeExist(req, resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    // 查询订单列表信息
    public void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String queryProductName = req.getParameter("queryProductName");
        String tempPid = req.getParameter("queryProviderId");
        String tempIspay = req.getParameter("queryIsPayment");
        String pageIndex = req.getParameter("pageIndex");
        int queryProviderId = 0;
        int queryIsPayment = 0;

        // 获取订单列表
        BillService billService = new BillServiceImpl();
        List<Bill> billList = null;

        // 第一次走这个请求，一定是第一页，页面大小固定的；
        int pageSize = 5;
        int currentPageNo = 1;

        if (queryProductName == null || queryProductName.equals("")) {
            queryProductName = "";
        }

        if (tempPid != null && !tempPid.equals("")) {
            try {
                queryProviderId = Integer.parseInt(tempPid);
            } catch (NumberFormatException ignored) {
            }
        }

        if (tempIspay != null && !tempIspay.equals("")) {
            try {
                queryIsPayment = Integer.parseInt(tempIspay);
            } catch (NumberFormatException ignored) {
            }
        }

        if (pageIndex != null && !pageIndex.equals("")) {
            try {
                currentPageNo = Integer.parseInt(pageIndex);
            } catch (NumberFormatException ignored) {
            }
        }
        // 获取订单的总数
        int totalCount = billService.getBillCount(queryProductName, queryProviderId, queryIsPayment);

        // 总页数支持
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo); // 设置当前页面
        pageSupport.setPageSize(pageSize); // 设置一页有多少条数据
        pageSupport.setTotalCount(totalCount); // 总共数据条数 里面会调用一个计算页数的方法

        // 总页数获取
        int totalPageCount = pageSupport.getTotalPageCount();

        // 控制首页和尾页
        // 吐过页面小于1了，就显示第一页的东西
        if (currentPageNo < 1) {
            currentPageNo = 1;
        } else if (currentPageNo > totalPageCount) {
            currentPageNo = totalPageCount;
        }

        // 获取订单列表展示
        billList = billService.getBillList(queryProductName, queryProviderId, queryIsPayment, currentPageNo, pageSize);
        req.setAttribute("billList", billList);

        // 分页参数回传页面
        req.setAttribute("totalCount", totalCount);
        req.setAttribute("currentPageNo", currentPageNo);
        req.setAttribute("totalPageCount", totalPageCount);

        providerService providerService = new providerServiceImpl();
        List<Provider> providerList = new ArrayList<Provider>();
        try {
            providerList = providerService.queryProvider();
        } catch (Exception ignored) {
        }
        req.setAttribute("providerList", providerList);

        // 将查询条件回显到页面
        req.setAttribute("queryProductName", queryProductName);
        req.setAttribute("queryProviderId", queryProviderId);
        req.setAttribute("queryIsPayment", queryIsPayment);

        // 返回前端
        try {
            req.getRequestDispatcher("billlist.jsp").forward(req, resp);
        } catch (ServletException e) {
            throw new ServletException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 添加订单
    public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("add()=======================================================");
        String billCode = req.getParameter("billCode");
        String productName = req.getParameter("productName");
        String productDesc = req.getParameter("productDesc");
        String productUnit = req.getParameter("productUnit");
        String productCount = req.getParameter("productCount");
        String totalPrice = req.getParameter("totalPrice");
        String providerId = req.getParameter("providerId");
        String isPayment = req.getParameter("isPayment");

        // 后端验证：检查所有必填字段是否为空
        if (billCode == null || billCode.trim().isEmpty() ||
                productName == null || productName.trim().isEmpty() ||
                productUnit == null || productUnit.trim().isEmpty() ||
                productCount == null || productCount.trim().isEmpty() ||
                totalPrice == null || totalPrice.trim().isEmpty() ||
                providerId == null || providerId.trim().isEmpty() ||
                "0".equals(providerId) ||
                isPayment == null || isPayment.trim().isEmpty()) {

            // 设置错误信息并返回添加页面
            req.setAttribute("error", "所有必填字段都不能为空！");

            // 将用户已填写的数据重新设置到request中，实现数据回显
            Bill billBack = new Bill();
            billBack.setBillCode(billCode != null ? billCode : "");
            billBack.setProductName(productName != null ? productName : "");
            billBack.setProductDesc(productDesc != null ? productDesc : "");
            billBack.setProductUnit(productUnit != null ? productUnit : "");
            billBack.setProductCount(productCount != null ? new BigDecimal(productCount) : null);
            billBack.setTotalPrice(totalPrice != null ? new BigDecimal(totalPrice) : null);
            billBack.setProviderId(providerId != null && !"0".equals(providerId) ? Integer.valueOf(providerId) : 0);
            billBack.setIsPayment(isPayment != null ? Integer.valueOf(isPayment) : 1);

            req.setAttribute("bill", billBack);
            req.getRequestDispatcher("billadd.jsp").forward(req, resp);
            return;
        }

        // 检查订单编码是否重复
        BillService billService = new BillServiceImpl();
        Bill existingBill = billService.selectBillCodeExist(billCode);
        if (existingBill != null) {
            // 设置错误信息并返回添加页面
            req.setAttribute("error", "订单编码已存在，请使用其他编码！");

            // 将用户已填写的数据重新设置到request中，实现数据回显
            Bill billBack = new Bill();
            billBack.setBillCode(billCode);
            billBack.setProductName(productName);
            billBack.setProductDesc(productDesc);
            billBack.setProductUnit(productUnit);
            billBack.setProductCount(new BigDecimal(productCount));
            billBack.setTotalPrice(new BigDecimal(totalPrice));
            billBack.setProviderId(Integer.valueOf(providerId));
            billBack.setIsPayment(Integer.valueOf(isPayment));

            req.setAttribute("bill", billBack);
            req.getRequestDispatcher("billadd.jsp").forward(req, resp);
            return;
        }

        // 验证数字字段格式
        try {
            new BigDecimal(productCount);
            new BigDecimal(totalPrice);
        } catch (NumberFormatException e) {
            req.setAttribute("error", "商品数量和总金额必须是有效的数字！");

            // 将用户已填写的数据重新设置到request中，实现数据回显
            Bill billBack = new Bill();
            billBack.setBillCode(billCode);
            billBack.setProductName(productName);
            billBack.setProductDesc(productDesc);
            billBack.setProductUnit(productUnit);
            billBack.setProductCount(null);
            billBack.setTotalPrice(null);
            billBack.setProviderId(Integer.valueOf(providerId));
            billBack.setIsPayment(Integer.valueOf(isPayment));

            req.setAttribute("bill", billBack);
            req.getRequestDispatcher("billadd.jsp").forward(req, resp);
            return;
        }

        Bill bill = new Bill();
        bill.setBillCode(billCode);
        bill.setProductName(productName);
        bill.setProductDesc(productDesc);
        bill.setProductUnit(productUnit);
        bill.setProductCount(new BigDecimal(productCount));
        bill.setTotalPrice(new BigDecimal(totalPrice));
        bill.setIsPayment(Integer.parseInt(isPayment));
        bill.setProviderId(Integer.parseInt(providerId));
        bill.setCreationDate(new Date());
        bill.setCreatedBy(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getId());

        boolean flag = billService.addBill(bill);
        if (flag) {
            resp.sendRedirect(req.getContextPath() + "/jsp/bill.do?method=query");
        } else {
            req.setAttribute("error", "添加订单失败，请重试！");

            req.setAttribute("bill", bill);
            req.getRequestDispatcher("billadd.jsp").forward(req, resp);
        }
    }

    // 获取订单提供商
    public void getProviderList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        List<Provider> providerList = null;
        providerService providerService = new providerServiceImpl();
        try {
            providerList = providerService.queryProvider();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        // 转换成json对象
        resp.setContentType("application/json");
        PrintWriter outPrintWriter = resp.getWriter();
        outPrintWriter.write(JSONArray.toJSONString(providerList));
        outPrintWriter.flush();
        outPrintWriter.close();
    }

    // 查询订单信息
    public void getBillId(HttpServletRequest req, HttpServletResponse resp, String url)
            throws ServletException, IOException {
        String billId = req.getParameter("billid");
        if (!StringUtils.isNullOrEmpty(billId)) {
            BillService billService = new BillServiceImpl();
            Bill bill = billService.getBillId(Integer.parseInt(billId));
            req.setAttribute("bill", bill);
            req.getRequestDispatcher(url).forward(req, resp);
        }

    }

    // 修改订单信息
    public void updateBill(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String billId = req.getParameter("id");
        String billCode = req.getParameter("billCode");
        String productName = req.getParameter("productName");
        String productDesc = req.getParameter("productDesc");
        String productUnit = req.getParameter("productUnit");
        String productCount = req.getParameter("productCount");
        String totalPrice = req.getParameter("totalPrice");
        String providerId = req.getParameter("providerId");
        String isPayment = req.getParameter("isPayment");

        // 后端验证：检查必填字段是否为空或只包含空格
        if (billCode == null || billCode.trim().isEmpty() ||
                productName == null || productName.trim().isEmpty() ||
                productUnit == null || productUnit.trim().isEmpty() ||
                productCount == null || productCount.trim().isEmpty() ||
                totalPrice == null || totalPrice.trim().isEmpty() ||
                providerId == null || providerId.trim().isEmpty() ||
                "0".equals(providerId) ||
                isPayment == null || isPayment.trim().isEmpty()) {

            // 设置错误信息
            req.setAttribute("error", "所有必填字段都不能为空或只包含空格！");

            // 将用户已填写的数据重新设置到request中，实现数据回显
            Bill billBack = new Bill();
            billBack.setId(Integer.valueOf(billId));
            billBack.setBillCode(billCode != null ? billCode : "");
            billBack.setProductName(productName != null ? productName : "");
            billBack.setProductDesc(productDesc != null ? productDesc : "");
            billBack.setProductUnit(productUnit != null ? productUnit : "");
            billBack.setProductCount(productCount != null ? new BigDecimal(productCount) : null);
            billBack.setTotalPrice(totalPrice != null ? new BigDecimal(totalPrice) : null);
            billBack.setProviderId(providerId != null && !"0".equals(providerId) ? Integer.valueOf(providerId) : 0);
            billBack.setIsPayment(isPayment != null ? Integer.valueOf(isPayment) : 1);

            req.setAttribute("bill", billBack);
            req.getRequestDispatcher("billmodify.jsp").forward(req, resp);
            return;
        }

        // 验证数字字段格式
        try {
            new BigDecimal(productCount);
            new BigDecimal(totalPrice);
        } catch (NumberFormatException e) {
            req.setAttribute("error", "商品数量和总金额必须是有效的数字！");

            // 将用户已填写的数据重新设置到request中，实现数据回显
            Bill billBack = new Bill();
            billBack.setId(Integer.valueOf(billId));
            billBack.setBillCode(billCode);
            billBack.setProductName(productName);
            billBack.setProductDesc(productDesc);
            billBack.setProductUnit(productUnit);
            billBack.setProductCount(null);
            billBack.setTotalPrice(null);
            billBack.setProviderId(Integer.valueOf(providerId));
            billBack.setIsPayment(Integer.valueOf(isPayment));

            req.setAttribute("bill", billBack);
            req.getRequestDispatcher("billmodify.jsp").forward(req, resp);
            return;
        }

        Bill bill = new Bill();
        bill.setId(Integer.parseInt(billId));
        bill.setBillCode(billCode);
        bill.setProductName(productName);
        bill.setProductDesc(productDesc);
        bill.setProductUnit(productUnit);
        bill.setProductCount(new BigDecimal(productCount));
        bill.setTotalPrice(new BigDecimal(totalPrice));
        bill.setProviderId(Integer.parseInt(providerId));
        bill.setIsPayment(Integer.parseInt(isPayment));
        bill.setModifyBy(((User) req.getSession().getAttribute(Constants.USER_SESSION)).getId());
        bill.setModifyDate(new Date());

        BillService billService = new BillServiceImpl();
        if (billService.updateBill(bill)) {
            resp.sendRedirect(req.getContextPath() + "/jsp/bill.do?method=query");
        } else {
            // 修改失败，设置错误信息并返回修改页面
            req.setAttribute("error", "修改订单信息失败，请重试！");

            // 数据回显
            req.setAttribute("bill", bill);
            req.getRequestDispatcher("billmodify.jsp").forward(req, resp);
        }
    }

    // 根据billCode查询bill
    public void selectBillCodeExist(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String billCode = req.getParameter("billCode");

        HashMap<String, String> resultMap = new HashMap<String, String>();
        if (StringUtils.isNullOrEmpty(billCode)) {
            resultMap.put("billCode", "exist");
        } else {
            BillService billService = new BillServiceImpl();
            Bill bill = billService.selectBillCodeExist(billCode);
            if (bill != null) {
                resultMap.put("billCode", "exist");
            } else {
                resultMap.put("billCode", "notexist");
            }
        }
        // 把resultMap转为json字符串以json的形式说输出
        // 配置上下文的输出类型
        resp.setContentType("application/json");
        // 从response对象中获取往外输出的writer对象
        PrintWriter outPrintWriter = resp.getWriter();
        // 把rusultMap转为json字符串 输出
        outPrintWriter.write(JSONArray.toJSONString(resultMap));
        outPrintWriter.flush(); // 刷新
        outPrintWriter.close(); // 关闭流
    }

    // 删除订单
    public void deleteBill(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String billId = req.getParameter("billid");
        Integer delId = 0;
        try {
            delId = Integer.parseInt(billId);
        } catch (Exception e) {
            delId = 0;
        }
        HashMap<String, String> resultMap = new HashMap<String, String>();
        if (delId <= 0) {
            resultMap.put("delResult", "notexist");
        } else {
            BillService billService = new BillServiceImpl();
            boolean flag = billService.deleteBill(delId);
            if (flag) {
                resultMap.put("delResult", "true");
            } else {
                resultMap.put("delResult", "false");
            }
        }

        // 返回JSON
        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
